package minSubArrayLen.java;

import java.util.Arrays;

public class minSubArrayLen {
    public static void main(String[] args) {
        int[] nums = new int[]{2, 3, 1, 2, 4, 3};
        System.out.println(minSubArrayLen2(7, nums));
    }

    /**
     * 暴力解法
     *
     * @param target
     * @param nums
     * @return
     */
    public static int minSubArrayLen(int target, int[] nums) {
        int p1 = 0, p2 = 0;
        int sum = 0;
        int min = 0;

        while (p1 < nums.length && p2 < nums.length) {
            sum = sum + nums[p2];
            if (sum < target) {
                p2++;
            } else {
                int len = p2 - p1 + 1;
                if (min == 0) {
                    min = len;
                }
                if (len < min) {
                    min = len;
                }
                p1++;
                p2 = p1;
                sum = 0;
            }
        }
        return min;
    }

    /**
     * 滑动
     * @param target
     * @param nums
     * @return
     */
    public static int minSubArrayLen2(int target, int[] nums) {
        int left = 0;
        int sum = 0;
        int result = Integer.MAX_VALUE;
        for (int right = 0; right < nums.length; right++) {
            sum += nums[right];
            while (sum >= target) {
                result = Math.min(result, right - left + 1);
                sum -= nums[left++];
            }
        }
        return result == Integer.MAX_VALUE ? 0 : result;
    }

}
